<?php
namespace App\Services\Classes;


use Illuminate\Support\Facades\Cache;

use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class Sms
{
    private $config;
    private $cache_prefix = 'sms_verify_code_';
    private $ttl = 300;

    public function __construct()
    {
        $this->config = config('easysms');
    }

    /**
     * Undocumented function
     *
     * @param [type] $phone
     * @param [type] $template
     * @param array $data
     * @return void
     */
    public function send($phone , $template , $data = []){
        try{
            $res = (new EasySms($this->config))->send($phone, [
                'template' => $template,
                'data' => $data
            ]);
        }catch(NoGatewayAvailableException $e){
            logger('sms-log:'.($e->getMessage())  );
            return false;
        }
        return $res;
    }

    /**
     * 发送验证码
     *
     * @param string $phone
     * @return void
     */
    public function sendVerifyCode($phone){
        $code = $this->setCodeInCache($phone);
        $data = [
            'code' => $code,
            'min'  => 5
        ];
        $template = 'SMS_174200191';
        return $this->send($phone , $template , $data);
    }

    /**
     * 返回验证码匹配
     *
     * @param [type] $phone
     * @param [type] $code
     * @return void
     */
    public function checkVerifyCode($phone , $code){
        if(!app()->environment('production') && $code == '1234'){
            return true;
        }
        return Cache::pull($this->cache_prefix . $phone) == $code;
    }

    /**
     * 存入缓存
     *
     * @param [type] $phone
     * @return void
     */
    public function setCodeInCache($phone){
        $code = str_pad(random_int(1, 9999), 4, 0, STR_PAD_LEFT);
        Cache::set($this->cache_prefix . $phone , $code ,  $this->ttl  );
        return $code;
    }

}
